package inc.gome.dynamic.datasource.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

public  class ClientDecode extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws IOException, ClassNotFoundException {

        System.out.println("=================> 客户端解码");
        int i = buf.readableBytes(); //可读取的大小
        while(i>=212) {
            byte[] bytes = new byte[212];
            //buf 得向前移动 否则会异常

            buf.getBytes(buf.readerIndex(), bytes);  //从哪里读取，读多少，但是readindex不变
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            ObjectInputStream oin = new ObjectInputStream(in);
            ResponseBody o = (ResponseBody) oin.readObject();
            System.out.println("客户端解码=========>" + o);

            i=i-212;
            buf.readBytes(bytes);
            out.add(o);
        }


    }
}